package internal

import (
	"encoding/json"
	"go.uber.org/zap"
	"gogogo-server/engine/module"
	"gogogo-server/protocol"
	"gogogo-server/share/http_helper"
	"net/http"
	"time"
)

type GameLogic struct {
	*module.LGLogic
}

func (gl *GameLogic) OnInit() error {
	gl.LGLogic = module.NewLGLogic(nil)
	return nil
}
func (gl *GameLogic) AfterInit() error {
	gl.GetServerCoroRPC().RegisterHandler("NewAgent", OnNewAgent)
	gl.GetServerCoroRPC().RegisterHandler("CloseAgent", OnCloseAgent)
	gl.GetServerCoroRPC().RegisterHandler(protocol.MsgEventHelloWorld, OnHelloWorld)
	return nil
}
func (gl *GameLogic) OnDestroy() {}

type TokenNode struct {
	Token string
}

func GetToken() string {
	return "SUCCESS"
	err, status, resp := http_helper.ClientInstance().Post("ws://127.0.0.1:8080", "application/json", "", 5*time.Second)
	if err != nil {
		zap.S().Fatalf("获取token报错:%s", err)
	}
	if status != http.StatusOK {
		zap.S().Fatalf("获取token失败:%d", status)
	}
	var tn TokenNode
	if err := json.Unmarshal(resp, &tn); err != nil {
		zap.S().Fatal("获取token失败:json序列化失败")
	}
	return tn.Token
}

/*
func (gl *GameLogic) Run(closeSig chan bool) {
	token := GetToken()
	zap.S().Infof("获得token:%s", token)
	// 连接WebSocket服务器
	conn, _, err := websocket.DefaultDialer.Dial("ws://127.0.0.1:8080", nil)
	if err != nil {
		zap.S().Fatalf("登录游戏服失败:%s", err)
	}
	defer conn.Close()

	hw := protocol.HelloWorld{
		Data: "HelloWorld",
	}
	data := map[string]any{"HelloWorld": hw}

	b, _ := json.Marshal(data)
	// 发送消息
	err = conn.WriteMessage(websocket.BinaryMessage, b)
	if err != nil {
		zap.S().Fatalf("发送消息失败:%s", err)
	}
	// 读取消息
	_, p, err := conn.ReadMessage()
	if err != nil {
		zap.S().Fatalf("读取消息失败:%s", err)
	}
	zap.S().Infof("收到服务器消息: %s ", string(p))
}
*/
